<template>
	<view class="tabbar-page">
		<HeaderNavTabarVue title="轨迹记录" />
		<map id="myMap" style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="markers"
			:polyline="polyline" show-location></map>
		<view>总里程: {{ totalDistance }} 米</view>
		<view class="" v-for="(item,index) in polyline[0].points" :key="index">
			<view class="">
				{{item.latitude}} {{item.longitude}}
			</view>
		</view>
		<button @click="startTracking">开始记录</button>
		<button @click="stopTracking">停止记录</button>
		<button @click="playAudio">播放音频</button>
		<!-- <button @click="pauseAudio">暂停音频</button> -->
		<button @click="stopAudio">停止音频</button>
	</view>
</template>

<script setup>
	import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
	import locationWatcher from '@/utils/location.js'
	// #ifdef APP-PLUS
	import {
		startForegroundService,
		stopForegroundService
	} from "@/uni_modules/hr-persist-track"
	//  #endif
	import {
		onLoad,
		onShow,
		onHide,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		defineProps,
		nextTick,
		onMounted,
		ref
	} from 'vue'
	import store from '@/store/index'
	const audioPlayer = ref(null)
	const isLoop = ref(false)


	const latitude = ref('') // 初始纬度
	const longitude = ref('') // 初始经度
	const markers = ref([]) // 标记点
	const polyline = ref([{
		points: [], // 轨迹点数组
		color: '#00FF00', // 轨迹线颜色
		width: 5, // 轨迹线宽度
		dottedLine: false // 是否为虚线
	}])
	const trackPoints = ref([]) // 记录轨迹点
	const startPosition = ref(null) // 开始位置
	const totalDistance = ref(0) // 总里程
	const locationWatcherId = ref(null) // 步骤生成的监听器id
	const isOnAppHide = ref(false) // 是否是熄屏模式

	onShow((() => {
		if (store._state.data.gps.latitude) {
			latitude.value = store._state.data.gps.latitude
			longitude.value = store._state.data.gps.longitude
			markers.value = store._state.data.gps.markers
			polyline.value = store._state.data.gps.polyline
			totalDistance.value = store._state.data.gps.totalDistance
			locationWatcherId.value = store._state.data.gps.locationWatcherId
			updateMap()
		} else {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					latitude.value = res.latitude,
						longitude.value = res.longitude
					markers.value = [{
						latitude: res.latitude,
						longitude: res.longitude,
						iconPath: '../../static/logo.png', //地图上的图标
						width: 40, //宽
						height: 40, //高
					}]
				},
				fail: (err) => {
					console.error('获取位置失败', err);
				}
			});
		}
	}))

	onLoad(() => {
		// 监听应用进入后台（熄屏）
		uni.onAppHide(() => {
			console.log('App is in background (screen off)');
			isOnAppHide.value = true
			// playAudio(); // 重新播放
		});

		// // 监听应用回到前台
		uni.onAppShow(() => {
			console.log('App is in foreground (screen on)');
			isOnAppHide.value = false
		});

		// 创建音频播放器
		audioPlayer.value = plus.audio.createPlayer('https://fileview.1nuoyun.com/files/ddsoft/rz_xcx/30s.mp3');

		// 监听播放完成事件
		audioPlayer.value.addEventListener('ended', () => {
			console.log('音频播放完成');
			if (isLoop.value) {
				playAudio(); // 重新播放
				console.log('再次获取位置')
				// startTracking() // 再次获取位置 形成轨迹
			}
		});

		// 监听错误事件
		audioPlayer.value.addEventListener('error', (err) => {
			console.error('音频播放错误', err);
		});
	})

	const playAudio = () => {
		// 播放音频
		audioPlayer.value.play();
		isLoop.value = true; // 开启循环播放
		console.log('开始播放');
		startTracking() // 开始获取位置
	}
	// const pauseAudio = () => {
	// 	// 暂停音频
	// 	audioPlayer.value.pause();
	// 	isLoop.value = false; // 关闭循环播放
	// 	console.log('暂停播放');
	// }
	const stopAudio = () => {
		// 停止音频
		audioPlayer.value.stop();
		isLoop.value = false; // 关闭循环播放
		console.log('停止播放');
	}

	// 开始记录轨迹
	const startTracking = () => {
	console.log('开始记录轨迹')
	uni.startLocationUpdate({
		success: () => {
			console.log('开始监听位置变化');
		},
		fail: (err) => {
			console.log('监听位置变化失败', err);
		}
	});

	uni.onLocationChange((res) => {
		console.log('位置变化', res);
		const point = {
			latitude: res.latitude,
			longitude: res.longitude
		};
		// 记录轨迹点
		trackPoints.value.push(point);

		// 记录里程
		if (startPosition.value) {
			const distance = calculateDistance(startPosition.value, point);
			totalDistance.value += distance;
			console.log(`当前里程: ${totalDistance.value.toFixed(2)} 米`);
		}
		startPosition.value = point;

		updateMap(); // 更新地图
	// uni.getLocation({
	// 	type: 'gcj02',
	// 	// 是否解析地址信息
	// 	geocode: true,
	// 	isHighAccuracy: false, // 高精度定位，会调用gps获取高精度坐标
	// 	success: res => {
	// 		const point = {
	// 			latitude: res.latitude,
	// 			longitude: res.longitude
	// 		};
	// 		// 记录轨迹点
	// 		trackPoints.value.push(point);

	// 		// 记录里程
	// 		if (startPosition.value) {
	// 			const distance = calculateDistance(startPosition.value, point);
	// 			totalDistance.value += distance;
	// 			console.log(`当前里程: ${totalDistance.value.toFixed(2)} 米`);
	// 		}
	// 		startPosition.value = point;

	// 		updateMap(); // 更新地图
	// 		// if (res.address) {
	// 		// 	cvsObj.address = res.address.country + res.address.city + res.address.district + res.address.street +
	// 		// 		res.address.streetNum + res.address.poiName
	// 		// }
	// 	},
	// 	fail: err => {
	// 		console.log(err, 'getCurrentAddress fail')
	// 	},
	// 	complete: e => {
	// 		console.log(e, 'getCurrentAddress complete')
	// 	}
	})
	// // #ifdef APP-PLUS
	// startForegroundService()
	// // #endif
	// locationWatcher.startLocationService(e => {
	// 	console.log('定位中', e)

	// 	if (!locationWatcherId.value) {
	// 		locationWatcherId.value = e.locationWatcherId //举例保存到data，实际可以缓存到全局
	// 		store._mutations.setLocationWatcherId[0](locationWatcherId.value)
	// 	}
	// 	const point = {
	// 		latitude: e.position.latitude,
	// 		longitude: e.position.longitude
	// 	};
	// 	// 记录轨迹点
	// 	trackPoints.value.push(point);

	// 	// 记录里程
	// 	if (startPosition.value) {
	// 		const distance = calculateDistance(startPosition.value, point);
	// 		totalDistance.value += distance;
	// 		console.log(`当前里程: ${totalDistance.value.toFixed(2)} 米`);
	// 	}
	// 	startPosition.value = point;

	// 	updateMap(); // 更新地图
	// }, (e) => {
	// 	console.log(e, '定位失败')
	// }, 10 * 1000)
	}

	const calculateDistance = (pos1, pos2) => {
		const R = 6371000; // 地球半径，单位米
		const dLat = (pos2.latitude - pos1.latitude) * Math.PI / 180;
		const dLon = (pos2.longitude - pos1.longitude) * Math.PI / 180;
		const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
			Math.cos(pos1.latitude * Math.PI / 180) * Math.cos(pos2.latitude * Math.PI / 180) *
			Math.sin(dLon / 2) * Math.sin(dLon / 2);
		const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		return R * c;
	}

	// 停止记录轨迹
	const stopTracking = () => {
		 uni.stopLocationUpdate(); // 停止位置监听
		// 停止音频
		audioPlayer.value.stop();
		isLoop.value = false; // 关闭循环播放
		console.log('停止播放');
		console.log('轨迹记录已停止');
		console.log(`总里程: ${totalDistance.value.toFixed(2)} 米`);
		// // #ifdef APP-PLUS
		// locationWatcher.closeLocationService(locationWatcherId.value);
		// stopForegroundService()
		// //  #endif
		// // #ifndef APP-PLUS
		// uni.offLocationChange()
		// //  #endif
		// locationWatcherId.value = null
		// store._mutations.setLocationWatcherId[0](null)
		store._mutations.setLatitude[0]('')
		store._mutations.setLongitude[0]('')
		store._mutations.setMarkers[0]([])
		store._mutations.setPolyline[0]([])
		store._mutations.setTotalDistance[0]('')
	}

	// 更新地图显示
	const updateMap = () => {
		if (trackPoints.value.length > 0) {
			const lastPoint = trackPoints.value[trackPoints.value.length - 1];
			latitude.value = lastPoint.latitude;
			longitude.value = lastPoint.longitude;

			// 更新标记点
			markers.value = [{
				id: 1,
				latitude: lastPoint.latitude,
				longitude: lastPoint.longitude,
				iconPath: '../../static/logo.png', //地图上的图标
				width: 40, //宽
				height: 40, //高
			}];

			// 更新轨迹线
			polyline.value = [{
				points: trackPoints.value,
				color: '#00FF00',
				width: 5,
				dottedLine: false
			}];

			store._mutations.setLatitude[0](latitude.value)
			store._mutations.setLongitude[0](longitude.value)
			store._mutations.setMarkers[0](markers.value)
			store._mutations.setPolyline[0](polyline.value)
			store._mutations.setTotalDistance[0](totalDistance.value)
		}
	}
</script>

<style lang="scss" scoped>
	.popup {
		padding: 40rpx;
		width: 50vw;
		height: 40vh;
		font-size: 40rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.popup-content {
			// margin-bottom: 20rpx;
		}
	}
</style>